'''

最锋利的剑的刀锋也无法与一颗和平的心的平静相匹敌。 ——易

'''

import base64
import json
import os
import re
import Utils
import Log
import time

rootDir = os.getcwd()
destDir = rootDir + './publish'
resoucesDir = rootDir + './resources'
projectDir = rootDir + '/src/web-mobile'
htmlDir = projectDir + '/index.html'
styleDir = projectDir + '/style.css'
engineDir = resoucesDir + '/engine'
ammoDir = resoucesDir + '/Ammo'
assetDir = projectDir + '/assets'
stime = time.time()


def convert1(url, str1):
    with open(url, 'rb') as f1:
        return str1 + str(base64.b64encode(f1.read()), encoding='utf-8')


def convert2(url):
    return ('%r' % Utils.fromFile(url))[1:-1]


pConvertFunctor = {
    '.json': lambda x: convert2(x),
    '.js': lambda x: convert2(x),
    '.wasm': lambda x: convert1(x, ''),
    '.png': lambda x: convert1(x, 'data:image/png;base64,'),
    '.jpg': lambda x: convert1(x, 'data:image/jpeg;base64,'),
    '.ttf': lambda x: convert1(x, ''),
    '.mp3': lambda x: convert1(x, ''),
    '.wav': lambda x: convert1(x, ''),
    '.bin': lambda x: convert1(x, '')
}

# load html
htmlContent = Utils.fromFile(htmlDir)
if htmlContent == None or len(htmlContent) == 0:
    Log.AppendLineLog(
        '%s content is empty or file does not exist' % htmlDir)

# clean html
htmlContent = re.sub(r'<script.*</script>', '', htmlContent)
htmlContent = re.sub(r'<!.*-->', '', htmlContent)

# toreal title
title = re.findall(r'<title>.*</title>', htmlContent)[0][23:-8]
htmlContent = re.sub(r'<title>.*</title>',
                     '<title>%s</title>' % title, htmlContent, 1)

# style
styleContent = Utils.StyleScript(Utils.fromFile(styleDir))
htmlContent = htmlContent.replace(
    '<link rel="stylesheet" type="text/css" href="style.css"/>', styleContent, 1)


# engine content
engineContent = Utils.fromFile(engineDir)
htmlContent = htmlContent.replace(
    r'</canvas>', '</canvas>\n'+engineContent+'\n_____________sign', 1)

# settingjson
settingJson = ('%r' % Utils.fromFile(projectDir + '/src/settings.json'))[1:-1]
htmlContent = htmlContent.replace(
    '____jsonSettings', 'var jsonSettings ='+settingJson, 1)


# ammo
ammoContent = Utils.fromFile(ammoDir)
htmlContent = htmlContent.replace(
    '_____________sign', ammoContent+'\n_____________sign', 1)


# 业务逻辑
lock = False
keepContent = ''
tsArr = {}


def handIndex(line: str):

    global lock
    if not lock:
        name = line.split(',', 1)[0][36:-1]
        if name.endswith('.ts'):
            line = line.replace('["cc"', '["./cc.js"', 1)
            tsArr[name] = line
        else:
            lock = True
    if lock:
        global keepContent
        keepContent += line


try:
    with open(assetDir+'/main/index.js', 'r', encoding='utf-8') as fp:
        for line in fp.readlines():
            if line != '\n':
                handIndex(line)
        launchJs = '<script>\n'
        logicJS = '<!-- Game Scripts. -->\n'
        for k, v in tsArr.items():
            logicJS += '<script id="%s">\n' % k+v+'</script>\n'
            launchJs += 'System.preload("./%s", getScriptById("%s"));\n' % (k, k)
        launchJs += '</script>'
except:
    Log.AppendLineTraceback();
finally:
    fp.close()

    for k, v in tsArr.items():
        name = './%s' % k
        keepContent = keepContent.replace(name, '../../%s' % k, 1)

    Utils.writeInFile(assetDir+'/main/index.js', keepContent)
    htmlContent = htmlContent.replace(
        '_____________sign', logicJS + launchJs + '\n<!-- Game Scripts. -->\n_____________sign', 1)


# 资源
def folder2JsonRes(dir, filter='', resMap={}):
    for root, dirs, files in os.walk(dir):
        path = root.replace(filter, '', 1).replace('\\', '/')
        for f in files:
            url = '%s/%s' % (path, f)
            ext = os.path.splitext(f)[1]
            resMap[url] = pConvertFunctor[ext](root + '/' + f)
    return resMap


jsonResMap = folder2JsonRes(projectDir + '/cocos-js/assets', projectDir +
                            '/cocos-js/')  # ammo.wasm-2f572f72.wasm
folder2JsonRes(assetDir, projectDir + '/', jsonResMap)  # 资源文件夹
jsonContent = json.dumps(jsonResMap, ensure_ascii=False)
Utils.writeInFile('./resMap.json', jsonContent)
htmlContent = re.sub('_____________sign', '<script>\nwindow.resMap = ' +
                     jsonContent + '\n</script>', htmlContent, 1)
Utils.writeInFile(destDir+'/index.html', htmlContent)

Log.AppendLineLog("useTime: " + str(time.time()-stime))
Log.ExportLog()
